import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users:[],//全部数据
    list:[],
    startIndex:0,//截取的开始下标
    endIndex:5,//截取的结束下标
    pageSize:5,//一页显示5条
    page:1,//页数
  },
  mutations: {
    GETDATA(state,data){//请求数据
      data.forEach(ele=>{//转化时间
        var time = new Date(ele.create_time*1000)
        var strTime = `${time.getFullYear()}年${time.getMonth()+1}月${time.getDate()}日
        ${time.getHours()}时${time.getMinutes()}分${time.getSeconds()}秒`;
        ele.create_time = strTime;
      })
      state.users = [...data];
      state.list = [...data];
    },
    CHANGEPAGE(state,page){//分页
      state.page = page;
      state.startIndex = (state.page - 1)*state.pageSize;
      state.endIndex = state.page*state.pageSize;
      if(state.endIndex>state.users.length){
        state.endIndex = state.users.length
      }
    },
    ONDELETE(state,item){//点击删除
      state.users.forEach((ele,index)=>{
        if(ele.id == item.id){
          state.users.splice(index,1);
        }
      })
    },
    ONCHANGECOUNT(state,obj){//点击修改完成
      console.log(obj);
      state.users.forEach(ele=>{
        if(ele.id == obj.id){
          ele.role_name = obj.username;
          ele.username = obj.users;
          ele.mobile = obj.mobile;
          ele.email = obj.email;
        }
      })
    }
  },
  actions: {
    GETDATA(context){//请求数据
      axios.get("http://localhost:8080/list.json").then(res=>{
        // console.log(res.data.data.users);
        context.commit("GETDATA",res.data.data.users);
      })
    }
  },
  getters:{//vuex中的计算属性
    ShowList(state){
      var temp = [];
      for(let index = state.startIndex ; index < state.endIndex ; index++){
          temp.push(state.users[index]);
      }
      return temp;
    }
  },
  modules: {
  }
})

